package job.manager.client.mb;

import com.icesoft.faces.component.ext.HtmlCommandButton;
import com.icesoft.faces.component.ext.RowSelectorEvent;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import job.manager.db.ec.AddressEB;
import job.manager.db.ec.ProfilesEB;
import job.manager.db.ec.UsersEB;
import job.manager.db.sb.ProfileRemote;
import job.manager.db.sb.UserRemote;
import job.manager.icefaces.core.SortableList;
import org.springframework.security.context.SecurityContextHolder;

/**
 *  The profile DataTable ManagedBean is responsible for connection to the Enterprise Beans
 *  and providing the pages/user with the information about profiles.
 *  Also resposible for editing and removing profiles.
 * 
 */
public class ProfileMBDT extends SortableList implements Serializable {
    @EJB
    private UserRemote userBean;

    @EJB
    private ProfileRemote profileBean;
    private Object[] proList;
    private ProfilesEB selectedProfile;
    private AddressEB address;
    private String addressid;
    ArrayList<AddressEB> addressList;
    // profileEB Names
    private static final String idColumnName = "Id";
    private static final String userNameColumnName = "fname";
    private static final String emailColumnName = "lname";
    private static final String isAdminColumnName = "number";
    private static final String profileColumnName = "comment";
    //addressEB rows in DB
    private String addressName;
    private String address1;
    private String address2;
    private String postCode;
    private String City;
    private String Country;
    private String phoneNumber;
    private String cellPhone;
    private String email;
    private String Comment;
    private int oldUserId;
    private String mapAddress;
    private boolean updateGmap;

    /** Creates a new instance of ProfileMBDT */
    public ProfileMBDT() {
        super(idColumnName);
    }

    @PostConstruct
    public void onInit() {
        oldUserId = 0;
        updateGmap = true;
        this.checkIfNotAdmin();
    }

    //for display actions if not admin
    protected void checkIfNotAdmin() {
        this.problemSolver();
        String userNamn = SecurityContextHolder.getContext().getAuthentication().getName();
        UsersEB currentUser = userBean.findUser(userNamn);
        if(!currentUser.getIsAdmin()) {
            ProfilesEB currentProfile = profileBean.getProfileInfo(currentUser.getProfileId());
            this.selectedProfile = currentProfile;
        }
    }

    //load profiles
    public void loadProfiles() {
        this.problemSolver();
        proList = profileBean.getAllProfiles().toArray();
    }

    //return the profiles for listing
    public Object[] getProfilelist() {
        if (proList == null) {
            this.loadProfiles();
        }
        if (!oldSort.equals(sortColumnName) ||
                oldAscending != ascending) {
            sort();
            oldSort = sortColumnName;
            oldAscending = ascending;
        }
        return proList;
    }


    //sorting functions for the DataTable
    @Override
    protected void sort() {
        Comparator comparator = new Comparator() {

            public int compare(Object o1, Object o2) {
                ProfilesEB p1 = (ProfilesEB) o1;
                ProfilesEB p2 = (ProfilesEB) o2;
                if (sortColumnName == null) {
                    return 0;
                }
                if (sortColumnName.equals("profilid")) {
                    return ascending ? new Integer(p1.getId()).compareTo(new Integer(p2.getId())) : new Integer(p2.getId()).compareTo(new Integer(p1.getId()));
                } else if (sortColumnName.equals("profilfname")) {
                    return ascending ? p1.getName1().compareTo(p2.getName1()) : p2.getName1().compareTo(p1.getName1());
                } else if (sortColumnName.equals("profillname")) {
                    return ascending ? p1.getName2().compareTo(p2.getName2()) : p2.getName2().compareTo(p1.getName2());
                } else if (sortColumnName.equals("profilnumber")) {
                    return ascending ? p1.getNumber().compareTo(p2.getNumber()) : p2.getNumber().compareTo(p1.getNumber());
                } else if (sortColumnName.equals("profilcomment")) {
                    return ascending ? p1.getComment().compareTo(p2.getComment()) : p2.getComment().compareTo(p1.getComment());
                } else {
                    return 0;
                }
            }
        };
        Arrays.sort(proList, comparator);
    }

    //returns if ascending is true
    @Override
    protected boolean isDefaultAscending(String sortColumn) {
        return true;
    }

    //actions that can be done by the user

    public void deleteAction(ActionEvent arg) {
        this.problemSolver();
        if (arg.getComponent() instanceof HtmlCommandButton) {
            if (this.selectedProfile != null) {
                profileBean.deleteProfile(selectedProfile);
                loadProfiles();
            }
        }
    }

    public void updateAction(ActionEvent arg) {
        this.problemSolver();
        if (this.selectedProfile != null) {
            profileBean.updateProfile(selectedProfile);
            address = new AddressEB(Integer.parseInt(this.addressid), address1, address2, postCode, City, Country, phoneNumber, cellPhone, email, addressName, selectedProfile);
            profileBean.updateAddress(address);

        }     

    }

    public void selectAction(RowSelectorEvent arg) {
        setMapAddress("Kalahari Desert, Africa");
        this.selectedProfile = (ProfilesEB) proList[arg.getRow()];
        if (selectedProfile!=null) {
            AddressEB ad = profileBean.getAddressByPk(selectedProfile.getId());
            if(ad!=null){
                setMapAddress(ad.getAddress1()+","+ad.getCity());
            }
        }
        setUpdateAddress(true);
    }

    //the bug fix for spring security
    private void problemSolver() {
        if (this.profileBean == null) {
            this.profileBean = ConnectFactory.getProfileBean();
        }
        if(this.userBean == null)
            this.userBean = ConnectFactory.getUserBean();
    }


    //set and get methods
    public boolean getIsEmployee() {
        if (this.selectedProfile != null) {
            return this.selectedProfile.getIsEmployee();
        } else {
            return true;
        }
    }

    public void setIsEmployee(boolean value) {
        if (this.selectedProfile != null) {
            this.selectedProfile.setIsEmployee(value);
            this.selectedProfile.setIsCustomer(!value);
        } else {
            this.selectedProfile = new ProfilesEB();
            this.selectedProfile.setIsEmployee(value);
            this.selectedProfile.setIsCustomer(!value);
        }
    }

    public ProfilesEB getSelectedProfile() {
        this.checkIfNotAdmin();
        if (this.selectedProfile != null) {
            return this.selectedProfile;
        } else {
            return new ProfilesEB();
        }
    }

    public void setAddressid(String addressid) {
        this.addressid = addressid;
    }

    public String getAddressid() {
        return this.addressid;
    }

    //this method is for getting the addresses, kind of special implementation
    public ArrayList<SelectItem> getAddressByPid() {
        ArrayList<SelectItem> itemList = new ArrayList<SelectItem>();
        setAddressName("");
        setAddress1("");
        setAddress2("");
        setCellPhone("");
        setCity("");
        setComment("");
        setCountry("");
        setEmail("");
        setPhoneNumber("");
        setPostCode("");
        if (selectedProfile != null) {
            addressList = new ArrayList(profileBean.getAddressByPid(selectedProfile.getId()));
            if (selectedProfile.getId() != oldUserId) {
                oldUserId = selectedProfile.getId();
                if (addressList.size() > 0) {
                    setAddressid(addressList.get(0).getId().toString());
                } else {
                    setAddressid(null);
                }
            }

            if (addressList.size() > 0) {
                if (this.addressid != null) {
                    AddressEB a = profileBean.getAddressByPk(Integer.parseInt(addressid));
                    setAddressName(a.getName());
                    setAddress1(a.getAddress1());
                    setAddress2(a.getAddress2());
                    setCellPhone(a.getCellPhone());
                    setCity(a.getCity());
                    setComment(a.getComment());
                    setCountry(a.getCountry());
                    setEmail(a.getEmail());
                    setPhoneNumber(a.getPhoneNumber());
                    setPostCode(a.getPostCode());
                } else {
                    setAddressName(addressList.get(0).getName());
                    setAddress1(addressList.get(0).getAddress1());
                    setAddress2(addressList.get(0).getAddress2());
                    setCellPhone(addressList.get(0).getCellPhone());
                    setCity(addressList.get(0).getCity());
                    setComment(addressList.get(0).getComment());
                    setCountry(addressList.get(0).getCountry());
                    setEmail(addressList.get(0).getEmail());
                    setPhoneNumber(addressList.get(0).getPhoneNumber());
                    setPostCode(addressList.get(0).getPostCode());
                }
                for (AddressEB addr : addressList) {
                    SelectItem a = new SelectItem();
                    a.setLabel(addr.getName());
                    a.setValue(addr.getId().toString());
                    itemList.add(a);
                }
            } else {
                SelectItem a = new SelectItem();
                a.setLabel("");
                itemList.add(a);
            }
        } else {
            SelectItem a = new SelectItem();
            a.setLabel("");
            itemList.add(a);
        }
        return itemList;
    }

    public String getAddressName() {
        return this.addressName;
    }

    public void setAddressName(String s) {
        this.addressName = s;
    }

    public String getCity() {
        return City;
    }

    public void setCity(String City) {
        this.City = City;
    }

    public String getComment() {
        return Comment;
    }

    public void setComment(String Comment) {
        this.Comment = Comment;
    }

    public String getCountry() {
        return Country;
    }

    public void setCountry(String Country) {
        this.Country = Country;
    }

    public String getAddress1() {
        return address1;
    }

    public void setAddress1(String address1) {
        this.address1 = address1;
    }

    public String getAddress2() {
        return address2;
    }

    public void setAddress2(String address2) {
        this.address2 = address2;
    }

    public String getCellPhone() {
        return cellPhone;
    }

    public void setCellPhone(String cellPhone) {
        this.cellPhone = cellPhone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getPostCode() {
        return postCode;
    }

    public void setPostCode(String postCode) {
        this.postCode = postCode;
    }

    public String getMapAddress() {
        setUpdateAddress(false);
        return mapAddress;
    }

    public void setMapAddress(String mapAddress) {
        this.mapAddress = mapAddress;
    }

    public boolean getUpdateAddress()
    {
        return updateGmap;
    }

    public void setUpdateAddress(boolean update)
    {
        this.updateGmap = update;
    }

    public boolean getIsEditing() {
        checkIfNotAdmin();
        return (this.selectedProfile == null);
    }
}
